import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class WebServer {

  public static void main(String[] arg) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(12345), 0);
    server.createContext("/cal", new AStatHandler());
    server.start();
  }

  static class AStatHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange exchange) {
      StringBuilder resBuilder = new StringBuilder("{\"path\":[");
      try {
        // 获得查询字符串(get)
        String queryString = exchange.getRequestURI().getQuery();
        queryString = queryString.substring(7, queryString.length() - 1);
        int[] input = new int[10];
        int i = -1;
        int zeroPos = -1;
        for (String s : queryString.split(",")) {
          i++;
          input[i] = Integer.parseInt(s);
          if (input[i] == 0)
            zeroPos = i;
        }
        System.out.println("收到请求：" + queryString);
        Object[] answer = new Astar_HRD().bfsHash(input, zeroPos);
        // System.out.println("答案已生成");
        // for (Integer k : input) {
        for (Object k : answer) {
          resBuilder.append((int) k + ",");
        }
        resBuilder.deleteCharAt(resBuilder.length() - 1);
        resBuilder.append("]}");
        System.out.println("答案已生成");
        exchange.sendResponseHeaders(200, 0);
        OutputStream os = exchange.getResponseBody();
        os.write(resBuilder.toString().getBytes());
        os.close();
      } catch (IOException ie) {
      } catch (Exception e) {
      }
    }
  }
}